<template>
  <el-dialog
    :close-on-click-modal="false"
    title="设备租赁合同结算明细"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号" prop="number">
            <el-input v-model="form.number" :disabled="true" placeholder="自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算数量" prop="settleCount">
            <el-input v-model="form.settleCount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算金额" prop="settleAmount">
            <el-input v-model="form.settleAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付日期" prop="payTime">
            <el-date-picker v-model="form.payTime" :disabled="disableForm" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付方式" prop="payType">
            <el-select v-model="form.payType" :disabled="disableForm" style="width: 100%;" placeholder="请选择支付方式">
              <el-option v-for="item in payTypes" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付单位" prop="payUnit">
            <el-select v-model="form.payUnit" :disabled="disableForm" style="width: 100%;" placeholder="请选择支付单位">
              <el-option label="公司" :value="1" />
              <el-option label="分公司" :value="2" />
              <el-option label="项目" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="2" :disabled="disableForm" />
      </el-form-item>

    </el-form>
    <div class="btns" style="padding-bottom: 10px">
      <el-button type="primary" @click="addRow">新增行</el-button>
      <el-button type="primary" @click="delRow">删除行</el-button>
    </div>
    <com-table
      v-model="selectRow"
      highlight-current-row
      :data="detailDataList"
      :columns="columns"
      :no-page="true"
    >
      <template v-slot:devDirCode="{row}">
        <el-input v-model="row.devDirCode" />
      </template>
      <template v-slot:devDirName="{row}">
        <el-input v-model="row.devDirName" />
      </template>
      <template v-slot:specification="{row}">
        <el-input v-model="row.specification" />
      </template>
      <template v-slot:unit="{row}">
        <el-input v-model="row.unit" />
      </template>
      <template v-slot:count="{row}">
        <el-input v-model="row.count" @input="inputCount" />
      </template>
      <template v-slot:startTime="{row}">
        <el-date-picker v-model="row.startTime" style="width:100%" type="date" :disabled="disableForm" />
      </template>
      <template v-slot:endTime="{row}">
        <el-date-picker v-model="row.endTime" style="width:100%" type="date" :disabled="disableForm" />
      </template>
      <template v-slot:unitPrice="{row}">
        <el-input v-model="row.unitPrice" @input="inputUnitPrice" />
      </template>
      <template v-slot:taxRate="{row}">
        <el-input v-model="row.taxRate" />
      </template>
      <template v-slot:taxes="{row}">
        <el-input v-model="row.taxes" />
      </template>
      <template v-slot:sumPrice="{row}">
        <el-input v-model="row.sumPrice" disabled />
      </template>
      <template v-slot:settleCount="{row}">
        <el-input v-model="row.settleCount" @input="getSettleAmount" />
      </template>
      <template v-slot:settleAmount="{row}">
        <el-input v-model="row.settleAmount" disabled />
      </template>
      <template v-slot:planLease="{row}">
        <el-input v-model="row.planLease" />
      </template>
      <template v-slot:remark="{row}">
        <el-input v-model="row.remark" />
      </template>

    </com-table>
    <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
    <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addDeviceLeaseContractSettleInfo, updateDeviceLeaseContractSettleInfo, getDeviceLeaseContractSettleInfoDetail, getDeviceLeaseContractDetailList } from '@/api/contractManage'
import { payTypes, payUnits } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'AddDeviceLeaseContractInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    id: {
      type: String,
      default() {
        return {}
      }
    },
    relateData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      selectRow: null,
      detailDataList: [],
      payTypes,
      payUnits,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        number: '',
        settleCount: '',
        settleAmount: '',
        payTime: '',
        payType: '',
        payUnit: '',
        remark: ''
      },
      fileList: [
      ],
      columns: [
        {
          label: '设备目录编码',
          prop: 'devDirCode',
          slot: 'devDirCode',
          width: '100'
        },
        {
          label: '设备目录名称',
          prop: 'devDirName',
          slot: 'devDirName',
          width: '100'
        },
        {
          label: '规格',
          slot: 'specification',
          prop: 'specification'
        },
        {
          label: '单位',
          slot: 'unit',
          prop: 'unit'
        },
        {
          label: '租赁数量',
          prop: 'count',
          slot: 'count',
          width: '150'
        },
        {
          label: '租赁开始时间',
          prop: 'startTime',
          slot: 'startTime',
          width: '160'
        },
        {
          label: '租赁结束时间',
          prop: 'endTime',
          slot: 'endTime',
          width: '160'
        },
        {
          label: '租赁单价',
          prop: 'unitPrice',
          slot: 'unitPrice',
          width: '150'
        },
        {
          label: '税率',
          slot: 'taxRate',
          width: '150'
        },
        {
          label: '税金',
          slot: 'taxes',
          width: '150'
        },
        {
          label: '租赁合价',
          prop: 'sumPrice',
          slot: 'sumPrice',
          width: '150'
        },
        {
          label: '计划租期',
          prop: 'planLease',
          slot: 'planLease',
          width: '150'
        },
        {
          label: '结算数量',
          prop: 'settleCount',
          slot: 'settleCount',
          width: '150'
        },
        {
          label: '结算金额',
          prop: 'settleAmount',
          slot: 'settleAmount',
          width: '150'
        },
        {
          label: '备注',
          prop: 'remark',
          slot: 'remark',
          width: '150'
        }

      ],
      rules: {
        settleCount: [
          { required: true, message: '请输入本次结算金额', trigger: 'change' }
        ],
        settleAmount: [
          { required: true, message: '请输入本次支付金额', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (this.optType === 'add') {
        getDeviceLeaseContractDetailList({ deviceLeaseContractInfoId: this.id }).then(res => {
          res.data.forEach(item => {
            delete item.id
          })
          this.detailDataList = res.data
        })
      }
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
  },
  methods: {
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          devDirCode: '',
          devDirName: '',
          specification: '',
          unit: '',
          count: '',
          startTime: '',
          endTime: '',
          unitPrice: '',
          taxRate: '',
          taxes: '',
          sumPrice: '',
          planLease: '',
          settleCount: '',
          settleAmount: '',
          remark: ''
        }
      ]
    },
    delRow() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    getDocDetail(id) {
      getDeviceLeaseContractSettleInfoDetail({ deviceLeaseContractSettleInfoId: id }).then(res => {
        // const { lstAttachment } = res.data || {}
        // if (lstAttachment && lstAttachment.length > 0) {
        //   this.fileList = lstAttachment
        // }
        if (res.data.lstAttachment && res.data.lstAttachment.length > 0) {
          this.fileList = res.data.lstAttachment
        }
        if (res.data.lstDeviceLeaseContractSettleDetail.length > 0) {
          this.detailDataList = res.data.lstDeviceLeaseContractSettleDetail
        }
        this.form = res.data.deviceLeaseContractSettleInfo
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          const params = {
            deviceLeaseContractSettleInfo: {
              ...formData,
              deviceLeaseContractInfoId: this.relateData.id,
              settleCount: Number(formData.settleCount),
              settleAmount: Number(formData.settleAmount)
              // ... this.optType === 'edit' ? {
              //   id: this.data.id
              // } : {}
            },
            lstDeviceLeaseContractSettleDetail: this.detailDataList,
            lstAttachment: this.fileList
          }
          if (this.optType === 'edit') {
            params.deviceLeaseContractSettleInfo.id = this.data.id
          } else {
            delete params.deviceLeaseContractSettleInfo.id
          }
          const fn = this.optType === 'add' ? addDeviceLeaseContractSettleInfo : updateDeviceLeaseContractSettleInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    inputCount() {
      this.detailDataList.forEach((item, index) => {
        if (item.count && item.unitPrice) {
          item.sumPrice = Number.parseFloat(item.count) * Number.parseFloat(item.unitPrice)
          item.sumPrice = Number.parseFloat(item.sumPrice).toFixed(2)
        } else {
          item.sumPrice = ''
        }
      })
    },
    inputUnitPrice() {
      this.detailDataList.forEach((item, index) => {
        if (item.count && item.unitPrice) {
          item.sumPrice = Number.parseFloat(item.count) * Number.parseFloat(item.unitPrice)
          item.sumPrice = Number.parseFloat(item.sumPrice).toFixed(2)
        } else {
          item.sumPrice = ''
        }
      })

      this.getSettleAmount()
    },
    // 获取结算金额汇总
    getSumSettleAmount() {
      let sum = 0
      this.detailDataList.forEach(item => {
        if (item.settleAmount) {
          sum += Number.parseFloat(item.settleAmount)
        }
      })
      this.form.settleAmount = sum.toFixed(2)
    },
    // 获取结算数量汇总
    getSumSettleCount() {
      let sum = 0
      this.detailDataList.forEach(item => {
        if (item.settleCount) {
          sum += Number.parseFloat(item.settleCount)
        }
      })
      this.form.settleCount = sum.toFixed(2)
    },
    // 获取结算金额
    getSettleAmount() {
      let unitPrice = 0
      let settleCount = 0
      if (this.selectRow.unitPrice) {
        unitPrice = this.selectRow.unitPrice
      }
      if (this.selectRow.settleCount) {
        settleCount = this.selectRow.settleCount
      }
      const settleAmount = Number.parseFloat(unitPrice) * Number.parseFloat(settleCount)
      this.selectRow.settleAmount = settleAmount.toFixed(2)

      this.getSumSettleCount()
      this.getSumSettleAmount()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
